package com.ruyuan.rapid.core.netty;

import com.ruyuan.rapid.core.LifeCycle;
import com.ruyuan.rapid.core.RapidConfig;
import com.ruyuan.rapid.core.helper.AsyncHttpHelper;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.EventLoopGroup;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;

import java.io.IOException;

/**
 * http客户端启动类, 主要用于下游服务的请求转发
 * @author mac
 */
@Slf4j
public class NettyHttpClient implements LifeCycle {

    private AsyncHttpClient asyncHttpClient;

    private RapidConfig rapidConfig;

    private DefaultAsyncHttpClientConfig.Builder clientBuilder;

    private EventLoopGroup eventLoopGroupWork;

    public NettyHttpClient(RapidConfig rapidConfig, EventLoopGroup eventLoopGroupWork) {
        this.rapidConfig = rapidConfig;
        this.eventLoopGroupWork = eventLoopGroupWork;
        init();
    }

    /**
     * 生命周期组件的初始化
     */
    @Override
    public void init() {
        this.clientBuilder = new DefaultAsyncHttpClientConfig.Builder()
                .setFollowRedirect(false)
                .setEventLoopGroup(eventLoopGroupWork)
                .setConnectTimeout(rapidConfig.getHttpConnectionTimeout())
                .setRequestTimeout(rapidConfig.getHttpRequestTimeout())
                .setAllocator(PooledByteBufAllocator.DEFAULT)
                .setCompressionEnforced(true)
                .setMaxConnections(rapidConfig.getHttpMaxConnections())
                .setMaxConnectionsPerHost(rapidConfig.getHttpConnectionPerHost())
                .setPooledConnectionIdleTimeout(rapidConfig.getHttpPooledConnectionIdleTimeout());
    }

    /**
     * 生命周期组件的启动方法
     */
    @Override
    public void start() {
        this.asyncHttpClient = new DefaultAsyncHttpClient(clientBuilder.build());
        AsyncHttpHelper.getInstance().initialized(asyncHttpClient);
    }

    /**
     * 关闭方法
     */
    @Override
    public void shutdown() {
        if (this.asyncHttpClient != null) {
            try {
                this.asyncHttpClient.close();
            } catch (IOException e) {
                log.error("NettyHttpClient shutdown error", e);
            }
        }
    }
}
